package com.atguigu.gmall.common.service;
/**
 * 封装消息发送
 */

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用于生产者发送消息方法
     * @param exchange
     * @param routingKey
     * @param msg
     */
    public void sendMessage(String exchange, String routingKey, Object msg) {
        //调用模板对象发送消息
        //1.构建相关数据,将相关数据存入Redis
        GmallCorrelationData correlationData = new GmallCorrelationData();
        //相关数据唯一标识
        String uuid = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(uuid);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(msg);
        //存入redis
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData), 1, TimeUnit.HOURS);
        //2.发送消息时候 选择既有业务消息还包括相关消息
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, correlationData);
    }

    /**
     * 生产者发送延迟消息消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param message 消息
     * @return
     */
    public void sendDelayMessage(String exchange,String routingKey,Object message,Integer ttlTime){
        //调用模版对象发送消息
        //1.构建相关数据,存入redis
        GmallCorrelationData correlationData = new GmallCorrelationData();
        //相关数据唯一标识
        String uuid = "mq:" + UUID.randomUUID().toString().replace("-", "");
        correlationData.setId(uuid);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(message);
        //存rides,设置存放时间1小时
        correlationData.setDelay(true);
        correlationData.setDelayTime(ttlTime);
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData),ttlTime + 100, TimeUnit.SECONDS);
        //2.发送消息时候既包含业务消息也包含相关消息,设置TTL时间
        rabbitTemplate.convertAndSend(exchange, routingKey, message,(msg) -> {
            //给消息改写延迟时间
            msg.getMessageProperties().setDelay(ttlTime * 1000);
            return msg;
        },correlationData);
    }
}